﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Transactions;
using ZenSystemService.Api.Business;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/sales")]
    [ApiController]
    public class SalesController : ControllerBase
    {
        private readonly UserService _userService;
        private readonly UserBusiness _userBusiness;
        private readonly DTOBusiness _dTOBusiness;
        private readonly TraineeOrderService _traineeOrderService;
        public SalesController(UserService userService,UserBusiness userBusiness, DTOBusiness dtoBusiness, TraineeOrderService traineeOrderService)
        {
            _userService = userService;
            _userBusiness = userBusiness;
            _dTOBusiness = dtoBusiness;
            _traineeOrderService = traineeOrderService;
        }

        /// <summary>
        /// 根据手机号查询学员主子账号
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("SearchTraineeMainSubAccountByMobile")]
        public async Task<ReturnObjectT<List<UserInfoResponse>>> SearchTraineeMainSubAccountByMobile(ReceiveObjectT<SearchTraineeMainSubAccountRequest> _receiveObjectT)
        {
            ReturnObjectT<List<UserInfoResponse>> _returnObjectT = new ReturnObjectT<List<UserInfoResponse>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "用户未登录";
                return _returnObjectT;
            }
            int userid = userModel.UserId;

            string mobile = _receiveObjectT.Data.Mobile;

            //根据手机号判断 用户是否已存在(主账号)
            User _user = await _userService.GetTraineeByPhoneAsync(mobile);
            if (_user != null)
            {
                List<UserInfoResponse> UserInfoResponseList = new List<UserInfoResponse>();
                UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user));
                if (_user.ParentUserId == null || _user.ParentUserId.Value == 0)//主账号
                {
                    List<User> SubUserList = await _userService.GetTraineeSubAccountList(_user.UserId);
                    if (SubUserList != null && SubUserList.Count > 0)
                    {
                        for (int i = 0; i < SubUserList.Count; i++)
                        {
                            UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(SubUserList[i]));
                        }
                    }
                }
                else//子账号
                {
                    User ParentUser = await _userService.GetUserByIdAsync(_user.ParentUserId.Value);
                    if (ParentUser != null)
                        UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(ParentUser));
                }
                if (UserInfoResponseList != null)
                    UserInfoResponseList = UserInfoResponseList.OrderBy(item => item.ParentUserId).ToList();
                _returnObjectT.Data = UserInfoResponseList;
            }

            _returnObjectT.Code = 1;
            return _returnObjectT;
        }

        /// <summary>
        /// 销售创建人员信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("SalesCreateUser")]
        public async Task<ReturnObjectT<List<UserInfoResponse>>> SalesCreateUser(ReceiveObjectT<SalesCreateUserRequest> _receiveObjectT)
        {
            ReturnObjectT<List<UserInfoResponse>> _returnObjectT=new ReturnObjectT<List<UserInfoResponse>> ();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "用户未登录";
                return _returnObjectT;
            }
            int userid = userModel.UserId;
            SalesCreateUserRequest salesCreateUserRequest = _receiveObjectT.Data;

            //判断手机号是否存在（不存在插入）
            string phone = salesCreateUserRequest.Mobile;
            //根据手机号判断 用户是否已存在(主账号)
            User _user = await _userService.GetTraineeByPhoneAsync(phone);
            List<UserInfoResponse> UserInfoResponseList = new List<UserInfoResponse>();
            if (_user == null)
            {
                CreateUserMainAccountDTO _createUserMainAccountDTO=new CreateUserMainAccountDTO();
                _createUserMainAccountDTO.Name = salesCreateUserRequest.Name;
                _createUserMainAccountDTO.Mobile = salesCreateUserRequest.Mobile;
                _createUserMainAccountDTO.Birthday = salesCreateUserRequest.Birthday;
                _createUserMainAccountDTO.Gender = salesCreateUserRequest.Gender;
                User newUser= await _userBusiness.CreateInitialTrainee(_createUserMainAccountDTO, userid, userid);
                if (newUser==null)
                {
                    _returnObjectT.Code = 0;
                    _returnObjectT.ErrorMsg = "创建用户失败";
                    return _returnObjectT;
                }
                UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(newUser));
            }
            else
            {
                UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user));
                if (_user.ParentUserId == null || _user.ParentUserId.Value == 0)//主账号
                {
                    List<User> SubUserList = await _userService.GetTraineeSubAccountList(_user.UserId);
                    if (SubUserList != null && SubUserList.Count > 0)
                    {
                        for (int i = 0; i < SubUserList.Count; i++)
                        {
                            UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(SubUserList[i]));
                        }
                    }
                }
                else//子账号
                {
                    User ParentUser = await _userService.GetUserByIdAsync(_user.ParentUserId.Value);
                    if (ParentUser != null)
                        UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(ParentUser));
                }
            }
            if (UserInfoResponseList != null)
                UserInfoResponseList = UserInfoResponseList.OrderBy(item => item.ParentUserId).ToList();
            _returnObjectT.Code = 1;
            _returnObjectT.Data = UserInfoResponseList;
            return _returnObjectT;
        }



        /// <summary>
        /// 销售创建子账号
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("SalesCreateSubAccount")]
        public async Task<ReturnObjectT<List<UserInfoResponse>>> SalesCreateSubAccount(ReceiveObjectT<SalesCreateSubUserRequest> _receiveObject)
        {
            ReturnObjectT<List<UserInfoResponse>> _returnObject = new ReturnObjectT<List<UserInfoResponse>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;

            TraineeCreateSubAccountRequest _traineeCreateSubAccountRequest=new TraineeCreateSubAccountRequest ();
            _traineeCreateSubAccountRequest.RealName = _receiveObject.Data.Name;
            _traineeCreateSubAccountRequest.Birthday = _receiveObject.Data.Birthday;
            _traineeCreateSubAccountRequest.Gender = _receiveObject.Data.Gender;
            _traineeCreateSubAccountRequest.TraineeRelationId = _receiveObject.Data.TraineeRelationId;
            _traineeCreateSubAccountRequest.TraineeRelationIRemark = _receiveObject.Data.TraineeRelationIRemark;

            bool isSuccess = await _userBusiness.CreateSubAccount(_traineeCreateSubAccountRequest, _receiveObject.Data.ParentUserId, userid);
            if (isSuccess == false)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "创建子账号失败";
                return _returnObject;
            }

            //加载学员
            List<UserInfoResponse> UserInfoResponseList = new List<UserInfoResponse>();
            User parentUser= _userService.GetUserById(_receiveObject.Data.ParentUserId);
            UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(parentUser));
            List<User> SubUserList = await _userService.GetTraineeSubAccountList(_receiveObject.Data.ParentUserId);
            if (SubUserList != null && SubUserList.Count > 0)
            {
                for (int i = 0; i < SubUserList.Count; i++)
                {
                    UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(SubUserList[i]));
                }
            }
            _returnObject.Code = 1;
            _returnObject.Data = UserInfoResponseList;
            return _returnObject;
        }

        /// <summary>
        /// 得到销售自己的销售学员订单
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetSalesOwnTraineeOrderList")]
        public async Task<ReturnObjectT<List<TraineeOrder>>> GetSalesOwnTraineeOrderList(ReceiveObjectT<TraineeOrderQuery2> _receiveObjectT)
        {
            ReturnObjectT<List<TraineeOrder>> _returnObject = new ReturnObjectT<List<TraineeOrder>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            int recordCount;
            IEnumerable<TraineeOrder> list = _traineeOrderService.GetSalesOwnTraineeOrderList(_receiveObjectT.Page, _receiveObjectT.PageSize, userid, out recordCount);
            List<TraineeOrder> TraineeOrderList = list.ToList();
            if (TraineeOrderList != null && TraineeOrderList.Count > 0)
            {
                IEnumerable<User> userlist = await _userService.GetAllUsersAsync();
                List<User> AllUserList = null;
                if (userlist != null)
                    AllUserList = userlist.ToList();
                for (int i = 0; i < TraineeOrderList.Count; i++)
                {
                    _dTOBusiness.JointSearchTraineeOrder(TraineeOrderList[i], AllUserList);
                }
            }
            _returnObject.Code = 1;
            _returnObject.Data = TraineeOrderList;
            _returnObject.RecordTotalCount = recordCount;
            return _returnObject;


        }
    }
}
